﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using TagLib;

namespace eComet
{
    class ToxUtils
    {
        public Dictionary<string, List<string>> files = new Dictionary<string, List<string>>();
        private String[] arrExt;
        private bool hasExtensions = false;
        public String[] argv;

        public ToxUtils()
        {
            this.argv = new String[1];
        }

        public ToxUtils(String[] argv)
        {
            this.argv = argv;
        }

        public static int IndexOfArray(string[] parms, string parm)
        {
            int salida = -1;
            for (int i = 0; i < parms.Length; i++)
            {
                if (parms[i].Contains(parm))
                {
                    return i;
                }
            }
            return salida;
        }

        public String getPaths()
        {
            return getPaths(this.argv);
        }

        public String getPaths(string[] argv)
        {
            String[] arrDir = ToxUtils.unirParams(argv, "/path");
            return arrDir[1].Replace('¬', ' ');
        }

        public Dictionary<string, string> getActions(string paramName)
        {
            return getActions(this.argv, paramName);
        }

        public Dictionary<string, string> getActions(string[] argv, string paramName)
        {
            Dictionary<string, string> exit = new Dictionary<string, string>();
            int indi = 0;
            while ((indi = ToxUtils.IndexOfArray(argv, paramName, indi)) != -1)
            {
                String[] parms = ToxUtils.unirParams(argv, paramName, indi);
                exit[parms[0]] = parms[1];
                if (indi >= argv.Length)
                    break;
                else
                    indi++;
            }
            return exit;
        }

        public Dictionary<string, List<string>> getFiles()
        {
            String paths = getPaths(this.argv);
            return getFiles(paths, "*");
        }

        public Dictionary<string, List<string>> getFiles(String[] extensions)
        {
            String paths = getPaths(this.argv);
            String strExt = String.Join(",", extensions);
            return getFiles(paths, strExt);
        }

        public Dictionary<string, List<string>> getFiles(String paths)
        {
            return getFiles(paths,"*");
        }

        public Dictionary<string, List<string>> getFiles(String paths,String extensions)
        {
            if (extensions.Equals(String.Empty) || extensions.Equals("*"))
            {
                hasExtensions = false;
            }
            else
            {
                hasExtensions = true;
            }
            arrExt = extensions.ToUpper().Split(',');
            foreach (String fileOrDir in paths.Split(';'))
            {
                recorreDirs(fileOrDir);
            }
            return files;
        }

        public void AddFile(String file)
        {
            string extension = Path.GetExtension(file).ToUpper();
            if (!hasExtensions || arrExt.Contains(extension))
            {
                if (!files.ContainsKey(extension))
                {
                    files[extension] = new List<string>();
                }
                files[extension].Add(file);
            }
        }

        public void recorreDirs(String fileOrDir)
        {
            //textBox1.Text += directorio + "\n";
            if (ToxUtils.IsDirectory(fileOrDir))
            {
                foreach (String dir in Directory.GetDirectories(fileOrDir))
                {
                    recorreDirs(dir);
                }
                foreach (String archivo in Directory.GetFiles(fileOrDir))
                {
                    AddFile(archivo);
                }
            }
            else
            {
                AddFile(fileOrDir);
            }
        }

        public static int IndexOfArray(string[] parms, string parm, int index)
        {
            int salida = -1;
            for (int i = index; i < parms.Length; i++)
            {
                if (parms[i].Contains(parm))
                {
                    return i;
                }
            }
            return salida;
        }


        public static string EditID3(string archivo, Dictionary<string, string> acciones)
        {
            return EditID3(archivo,acciones,archivo.Split('.').Last());
        }


        public static string EditID3(string archivo,Dictionary<string,string> acciones,string tipo)
        {
            string salida = null;
            string[] arr = new string[1];
            try
            {
                TagLib.File file = TagLib.File.Create(archivo);
                foreach (String accion in acciones.Keys)
                {
                    switch (accion)
                    {
                        case "/setgen":
                            arr[0] = acciones[accion];
                            file.Tag.Genres = arr;
                            break;
                        case "/setalb":
                            file.Tag.Album = acciones[accion];
                            break;
                        case "/setart":
                            arr[0] = acciones[accion];
                            file.Tag.Artists = arr;
                            break;
                        case "/setson":
                            file.Tag.Title = acciones[accion];
                            break;
                        default:
                            //textBox1.Text = archivo + "\n" + textBox1.Text;
                            break;
                    }
                }
                file.Save();
            }
            catch (System.UnauthorizedAccessException e)
            {
                if ((System.IO.File.GetAttributes(archivo) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    System.IO.File.SetAttributes(archivo, FileAttributes.Normal);
                    EditID3(archivo, acciones, tipo);
                }
            }
            catch (TagLib.CorruptFileException e)
            {
                salida = archivo + "\n" + e.GetType().ToString() + "\n" + e.Message;
            }
            catch(Exception e)
            {
                salida = archivo + "\n" + e.GetType().ToString()+"\n"+e.Message;
            }
            return salida;
        }

        public static int LastIndexOfArray(string[] parms, string parm)
        {
            int salida = -1;
            for (int i = 0; i < parms.Length; i++)
            {
                if (parms[i].Contains(parm))
                {
                    salida = i;
                }
            }
            return salida;
        }

        public Dictionary<String, String> getParam(String[] args, String param)
        {
            Dictionary<String, String> exit = new Dictionary<String, String>();
            return exit;
        }

        public static string[] unirParams(string[] parms, string parm)
        {
            return unirParams(parms, parm, 0);
        }

        public static string[] unirParams(string[] parms, string parm, int index)
        {
            int indice = IndexOfArray(parms, parm, index) + 1;
            String nomPar = parms[indice - 1];
            String nomDir = "";
            if (indice < parms.Length)
            {
                if (!parms[indice].StartsWith("/"))
                {
                    bool continuar = true;
                    do
                    {
                        nomDir += parms[indice++] + " ";
                        if (indice >= parms.Length)
                        {
                            continuar = false;
                        }
                        else
                        {
                            if (parms[indice].StartsWith("/"))
                            {
                                continuar = false;
                            }
                        }
                    }
                    while (continuar);
                    nomDir = nomDir.Trim();
                }
            }
            string[] salida = { nomPar, nomDir };
            return salida;
        }

        public static bool IsDirectory(string file)
        {
            FileAttributes attr = System.IO.File.GetAttributes(file);
            //detect whether its a directory or file
            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                return true;
            else
                return false;
        }

    }
}
